#include "gameroom.h"
#include "ui_gameroom.h"
#include "login.h"

gameRoom::gameRoom(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::gameRoom)
{
    ui->setupUi(this);
}

gameRoom::~gameRoom()
{
    delete ui;
}

void gameRoom::ws_room(QString ssid)
{
    _ssid = ssid;//保存session id
    //构造：QWebSocket(const QString &origin = QString(), QWebSocketProtocol::Version version = QWebSocketProtocol::VersionLatest, QObject *parent = nullptr)
    //使用给定的源，要使用的协议版本和parent创建一个新的QWebSocket 。
    ws = new QWebSocket;//new一个客户端对象
    ws->setParent(this);
    QString name_ws = "/room";
    QNetworkRequest ws_request(QUrl(WS_URL + name_ws));
    ws_request.setRawHeader("Cookie", ssid.toUtf8());
    ws->open(ws_request);
    //2.判断是否连接
    connect(ws, &QWebSocket::connected, this, &gameRoom::connectHandle);//连接成功
    connect(ws, &QWebSocket::disconnected, this, &gameRoom::disConnectHandle);//断开连接
    //connect(ws, &QWebSocket::error, this, &gameRoom::errorHandle);//连接错误
    //4.接收数据
    connect(ws, &QWebSocket::textMessageReceived, this, &gameRoom::recvMessageHandle);//发送消息
}

void gameRoom::closeEvent(QCloseEvent *event)
{
    (void)event;
    //QMessageBox::information(this, "客户端消息", "关闭房间连接", QMessageBox::Ok);
    //ws->close();//关闭房间连接
    qDebug() << "退出房间页面";

}

void gameRoom::paintEvent(QPaintEvent *)
{
    paint = new QPainter;
    paint->begin(this);//主窗口
    //绘制图片
    QPixmap pixmap1(":/cat.jpg");
    //图片缩放
    paint->drawPixmap(0, 0, 1073, 544, pixmap1);
    //绘制图片
    QPixmap pixmap2(":/sky.jpeg");
    //painter.drawPixmap(0, 0, pixmap2);
    //图片缩放
    paint->drawPixmap(158, 98, 306, 306, pixmap2);

    paint->setPen(QPen(Qt::white, 1, Qt::SolidLine));//钢笔工具：颜色，线号，实线
    //画SIZE+1条横线
    for(int i = 0; i < SIZE + 1; i++)
    {
      paint->drawLine(x, y + WIDTH * i, x + WIDTH * SIZE, y + WIDTH * i);//画线函数：x1,y1,x2,y2:画从(x1,y1)到(x2,y2)的线
    }
    //画SIZE+1条竖线
    for(int i = 0; i < SIZE + 1; i++)
    {
      paint->drawLine(x + WIDTH * i, y, x + WIDTH * i, y + WIDTH * SIZE);
    }
    //颜色填充
    QBrush brush;
    //paint->setPen(QPen(Qt::black, 1, Qt::SolidLine));
    //画SIZE * SIZE个棋子
    qDebug("move: %d %d",row, col);
    for(int i = 0; i < SIZE + 1; i++)
    {
        for(int j = 0; j < SIZE + 1; j++)
        {
            if(chess_board[i][j] != 0)
            {
                if(chess_board[i][j] == 1)
                {
                    paint->setPen(QPen(Qt::white, 1, Qt::SolidLine));//钢笔工具：颜色，线号，实线
                    brush.setColor(QColor(255, 255, 255));//设置填充颜色
                    brush.setStyle(Qt::SolidPattern);//设置填充风格
                    paint->setBrush(brush);
                    paint->drawEllipse(QPoint(WIDTH * i + 160, WIDTH * j + 100), WIDTH / 2 - 2, WIDTH / 2 - 2);//画圆
                }
                else
                {
                    paint->setPen(QPen(Qt::black, 1, Qt::SolidLine));//钢笔工具：颜色，线号，实线
                    brush.setColor(QColor(0, 0, 0));//设置填充颜色
                    brush.setStyle(Qt::SolidPattern);//设置填充风格
                    paint->setBrush(brush);
                    paint->drawEllipse(QPoint(WIDTH * i + 160, WIDTH * j + 100), WIDTH / 2 - 2, WIDTH / 2 - 2);//画圆
                }
            }
        }
    }

    //paint->drawEllipse(QPoint(mouseX, mouseY), WIDTH / 2 - 2, WIDTH / 2 - 2);//画圆
    paint->end();
}

void gameRoom::mousePressEvent(QMouseEvent *event)
{
    if(!is_me)
    {
        QMessageBox::information(this, "客户端消息", "等待对方走棋...", QMessageBox::Ok);
        return;
    }
    row = (event->x() - 160) / WIDTH;
    col = (event->y() - 100) / WIDTH;
    //向服务器发送响应后，再绘制棋子
    if(chess_board[row][row] == 0
       && row >= 0 && col >= 0
       && row < SIZE + 1
       && col < SIZE + 1)
    {
        sendChess(row, col);
    }

    update();
}

void gameRoom::put_chess(bool me)
{
    if(me)
    {
        ui->label_connect->setText("轮到己方走棋...");
    }
    else
    {
        ui->label_connect->setText("轮到对方走棋...");
    }
}

void gameRoom::sendChess(int row, int col)
{
    QJsonObject req;//创建一个json对象
    req.insert("optype", QJsonValue("put_chess"));
    req.insert("room_id", QJsonValue(room_info["room_id"].toInt()));
    req.insert("uid", QJsonValue(room_info["uid"].toInt()));
    req.insert("row", QJsonValue(row));
    req.insert("col", QJsonValue(col));
    ws->sendTextMessage(QJsonDocument(req).toJson());
}

void gameRoom::connectHandle()
{
    qDebug() << "websocket_room连接成功";
}

void gameRoom::disConnectHandle()
{
    qDebug() << "websocket_room断开连接";
}

void gameRoom::recvMessageHandle(const QString &msg)
{
    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(msg.toUtf8(), &jsonError);
    if(jsonError.error == QJsonParseError::NoError)
    {
        QJsonObject jsonObject = jsonDocument.object();
        //QMessageBox::information(this, "服务端响应", msg, QMessageBox::Ok);
        //1.收到room_ready之后进行房间的初始化
        //  1.将房间信息保存起来
        if(jsonObject["optype"] == "room_ready")
        {
            if(jsonObject["result"].toBool() == true)
            {
                //QMessageBox::information(this, "客户端消息", "房间准备好了", QMessageBox::Ok);
                room_info = jsonObject;
                is_me = room_info["uid"].toInt() == room_info["white_id"].toInt() ? true : false;
                put_chess(is_me);//该谁下棋
            }
            else
            {
                ws->close();//断房间长连接开连接
                //QMessageBox::information(this, "客户端消息", "断开房间长连接",QMessageBox::Ok);
                gameHall* gamehall = new gameHall;
                gamehall->get_info(_ssid);//获取用户信息
                gamehall->ws_hall(_ssid);//建立长连接
                this->close();
                gamehall->show();
            }
        }

        //2.走棋动作
        else if(jsonObject["optype"] == "put_chess")
        {
            if(jsonObject["result"].toBool() == false)
            {
                //QMessageBox::critical(this, "服务端响应", msg, QMessageBox::Ok);
                return;
            }
            //QMessageBox::information(this, "客户端消息", "进行下棋动作", QMessageBox::Ok);
            is_me = jsonObject["uid"].toInt() == room_info["uid"].toInt() ? false : true;//切换走棋的人
            color_id = jsonObject["uid"].toInt() == room_info["white_id"].toInt() ? 1 : 2;
            //设置棋盘信息
            int js_row = jsonObject["row"].toInt();
            int js_col = jsonObject["col"].toInt();
            if(js_row != -1 && js_col != -1)
            {
                chess_board[js_row][js_col] = color_id;
            }
            //是否有胜利者
            if(jsonObject["winner"].toInt() == 0)
            {
                return;
            }
            if(room_info["uid"].toInt() == jsonObject["winner"].toInt())
            {
                ui->label_connect->setText(jsonObject["reason"].toString().toUtf8());
            }
            else
            {
                ui->label_connect->setText("你输了。");
            }
        }
        //3.聊天动作
        else if(jsonObject["optype"] == "chat")
        {
            //QMessageBox::information(this, "客户端消息", "进行聊天动作", QMessageBox::Ok);
            if(jsonObject["result"].toBool() == false)
            {
                QMessageBox::information(this, "客户端消息", jsonObject["reason"].toString(), QMessageBox::Ok);
                return;
            }
            else
            {
                if(room_info["uid"].toInt() == jsonObject["uid"].toInt())
                {
                    text += "<p align=\"right\">" + jsonObject["message"].toString() + ":我</p></br>";
                    ui->textBrowser->setHtml(text);
                }
                else
                {
                    text += "<p align=\"left\">对手:" + jsonObject["message"].toString() + "</p></br>";
                    ui->textBrowser->setHtml(text);
                }
                ui->lineEdit_input->setText("");
            }
        }
    }
}

//返回大厅
void gameRoom::on_pushButton_return_gameHall_clicked()
{
    ws->close();//断房间长连接开连接
    //QMessageBox::information(this, "客户端消息", "断开房间长连接",QMessageBox::Ok);
    gameHall* gamehall = new gameHall;
    gamehall->get_info(_ssid);//获取用户信息
    gamehall->ws_hall(_ssid);//建立长连接
    this->close();
    gamehall->show();
}

void gameRoom::on_pushButton_send_clicked()
{
    QJsonObject req;//创建一个json对象
    req.insert("optype", QJsonValue("chat"));
    req.insert("room_id", QJsonValue(room_info["room_id"].toInt()));
    req.insert("uid", QJsonValue(room_info["uid"].toInt()));
    req.insert("message", QJsonValue(ui->lineEdit_input->text()));
    ws->sendTextMessage(QJsonDocument(req).toJson());
}
